package conf

import (
	"github.com/spf13/viper"
	"log"
	"strings"
)

var defaultPath = "config.yml"
var storePath = ""
var storeid = ""
var maxsize = 0

type Config struct {
	FilePath string
	Viper    *viper.Viper
	Env      *viper.Viper
}

func (c *Config) SetStorePath() {
	storePath = c.Viper.GetString("storage.path")
}

func SetMaxSize(size int) {
	maxsize = size
}

func GetMaxSize() int {
	return maxsize
}

func SetStoreid(sid string) {
	storeid = sid
}

func GetStoreid() string {
	return storeid
}

//加载配置
func LoadConfig(path string) *Config {
	var cfg *Config
	var cfgPath string
	env := viper.New()
	env.AutomaticEnv()
	v := viper.New()
	v.SetConfigType("yml")
	if path == "" {
		cfgPath = defaultPath
	} else {
		cfgPath = path
	}
	v.SetConfigFile(cfgPath)
	// 读取配置文件
	err := v.ReadInConfig()
	if err != nil {
		log.Println("读取配置文件失败, 异常信息 : ", err)
	}
	cfg = &Config{
		FilePath: defaultPath,
		Viper:    v,
		Env:      env,
	}
	cfg.SetStorePath()
	return cfg
}

func GetStorePath() string {
	return storePath
}

//获取环境变量配置
func (c *Config) GetEnvValue(key string) string {
	placeholder := c.Viper.GetString(key)
	index := strings.Index(placeholder, "{")
	temp := placeholder[index+1:]
	lastindex := strings.LastIndex(temp, "}")
	value := temp[:lastindex]
	envindex := strings.Index(value, ":")
	envkey := value[:envindex]
	defaultvalue := value[envindex+1:]
	log.Println("###envkey", envkey, "defaultvalue:", defaultvalue)
	if c.Env.IsSet(envkey) {
		//存在
		return c.Env.GetString(envkey)
	}
	return defaultvalue
}
